use std::{borrow::Borrow, collections::HashMap};

use chrono::NaiveDateTime;
use rusqlite::{Connection, Result};
use serde::de::value;

use crate::{todo_list::todo_item::TodoItem, GLOBAL_CONFIG, TODOLIST};

pub fn load_all() -> Result<()> {
    let conn = Connection::open(GLOBAL_CONFIG.lock().unwrap().todo_list.db_file.clone())?;
    conn.execute_batch(
        "BEGIN;
        CREATE TABLE IF NOT EXISTS todolist(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                content TEXT,
                status TEXT,
                priority TEXT,
                created_at TEXT,
                updated_at TEXT
                );
            COMMIT;",
    )?;

    let mut stmt = conn.prepare(
        "
        SELECT * FROM todolist
        ORDER BY created_at DESC
        ",
    )?;

    let todolist_iter = stmt.query_map([], |row| {
        let created_at_str: String = row.get(4)?; // 获取时间字符串
        let created_at = NaiveDateTime::parse_from_str(&created_at_str, "%Y-%m-%d %H:%M:%S")
            .expect("解析时间格式失败");

        let updated_at_str: String = row.get(5)?; // 获取时间字符串
        let updated_at = NaiveDateTime::parse_from_str(&updated_at_str, "%Y-%m-%d %H:%M:%S")
            .expect("解析时间格式失败");
        Ok(TodoItem {
            id: row.get(0)?,
            content: row.get(1)?,
            status: row.get(2)?,
            priority: row.get(3)?,
            created_at,
            updated_at,
        })
    })?;

    let mut todolist = TODOLIST.lock().unwrap();
    for item in todolist_iter {
        let item = item?;
        todolist.insert(item.id, item);
    }
    Ok(())
}

#[tauri::command]
pub fn query_todolist() -> HashMap<String, Vec<TodoItem>> {
    // 获取 TODOLIST 的锁
    let todolist = TODOLIST.lock().unwrap();
    
    // 创建一个 HashMap 来存储分组后的数据
    let mut grouped_items: HashMap<String, Vec<TodoItem>> = HashMap::new();

    // 遍历 TODOLIST 中的所有 TodoItem
    for (_id, item) in todolist.iter() {
        // 将 created_at 转换为 "YYYY-MM-DD" 的字符串格式
        let date_str = item.created_at.format("%Y-%m-%d").to_string();

        // 按照日期分组，将 item 放入对应的 Vec 中
        grouped_items
            .entry(date_str)
            .or_insert_with(Vec::new)
            .push(item.clone());
    }

    grouped_items
}
